#!/usr/bin/env python
# encoding: utf-8

from app.views.webapi import route_api
from  flask import request,jsonify,g
import requests,json,decimal

from app import db
from app.model import User
from app.model import Electronic
from app.model import ElectronicBoom
from app.model import ElectronicBoomItem

from app.common.libs.Helper import getFormatDate, getCurrentDate
from app.common.libs.UserService import UserService


@route_api.route("/electronicBoom/fetchall",methods = [ "GET","POST" ])
def electronicBoomFetchall():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}
    user_info = UserService.getUserInfo(request)
    data = db.session.query( ElectronicBoom )\
                .filter(ElectronicBoom.user_id == User.id)\
                .filter(User.id == user_info.id)\
                .all()
    items = [{ 'id':item.id, 'name':item.name } for item in data]
    resp['data']['items'] = items
    return jsonify( resp )

@route_api.route("/electronicBoom/list",methods = [ "GET","POST" ])
def electronicBoomList():
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}
    req = request.values
    page = int( req['page'] ) if 'page' in req else 0
    limit = int( req['limit'] ) if 'limit' in req else 0
    offset = ( page - 1 ) * limit

    user_info = UserService.getUserInfo(request)
    query = db.session.query( ElectronicBoom)\
                .filter(ElectronicBoom.user_id == User.id)\
                .filter(User.id == user_info.id)
    # 获取总数
    total = query.count()
    # 获取元器件boom
    electronic_boom_list = query.order_by(ElectronicBoom.updated_time).offset( offset ).limit( limit ).all()

    items = [{
            'id':item.id,
            'name':item.name,
            'note':item.note,
            'updated_time':getFormatDate(item.updated_time)
        } for item in electronic_boom_list]

    resp['data']['items'] = items
    resp['data']['total'] = total

    return jsonify( resp )

@route_api.route("/electronicBoom/create",methods = [ "GET","POST" ])
def electronicBoomCreate():
    resp = { 'code':20000,'message':'创建成功~', 'data':{}}

    if request.method == 'POST':
        data = request.get_data()
        json_data = json.loads(data.decode('utf-8'))

        user_info = UserService.getUserInfo(request)

        boom_model = ElectronicBoom()
        boom_model.name = json_data['name']
        boom_model.note = json_data['note']
        boom_model.created_time = boom_model.updated_time = getCurrentDate()
        boom_model.user_id = user_info.id

        db.session.add(boom_model)
        db.session.commit()

    return jsonify( resp )

@route_api.route("/electronicBoom/delete/<int:id>",methods = [ "GET","POST" ])
def electronicBoomDelete(id):
    resp = { 'code':20000,'message':'删除成功~', 'data':{}}
    if request.method == 'POST':
        boom_info = ElectronicBoom.query.filter_by( id=id ).first()
        if not boom_info:
            resp['code'] = -1
            resp['message'] = 'boom单不存在'
            return jsonify( resp )
        db.session.delete(boom_info)
        db.session.commit()
    return jsonify( resp )

@route_api.route("/electronicBoom/update/<int:id>",methods = [ "GET","POST" ])
def electronicBoomUpdate(id):
    resp = { 'code':20000,'message':'编辑成功~', 'data':{}}
    if request.method == 'POST':
        boom_info = ElectronicBoom.query.filter_by( id=id ).first()
        if not boom_info:
            resp['code'] = -1
            resp['message'] = 'boom单不存在'
            return jsonify( resp )
        data = request.get_data()
        json_data = json.loads(data.decode('utf-8'))
        boom_info.name = json_data['name']
        boom_info.note = json_data['note']
        boom_info.updated_time = getCurrentDate()
        db.session.commit()
    return jsonify( resp )


## boom单条目相关api


@route_api.route("/electronicBoomItem/list/<int:id>",methods = [ "GET","POST" ])
def electronicBoomItemList(id):
    resp = { 'code':20000,'message':'操作成功~', 'data':{}}
    req = request.values

    page = int( req['page'] ) if 'page' in req else 0
    limit = int( req['limit'] ) if 'limit' in req else 0
    offset = ( page - 1 ) * limit

    query = db.session.query( ElectronicBoomItem, Electronic)\
            .filter(ElectronicBoomItem.electronic_boom_id == id)\
            .filter(ElectronicBoomItem.electronic_id == Electronic.id)
    # 获取总数
    total = query.count()
    # 获取元器件boom
    model_list = query.order_by(Electronic.name).offset( offset ).limit( limit ).all()

    items = [{
            'id':item.id,
            'count':item.count,
            'electronic':{
                    'id': electronic.id,
                    'name': electronic.name,
                    'price': str(electronic.price),
                    'spec': electronic.spec,
                    'package': electronic.package,
                    'stock': electronic.stock
                }
            } for item,electronic in model_list]

    resp['data']['items'] = items
    resp['data']['total'] = total

    return jsonify( resp )

@route_api.route("/electronicBoomItem/delete",methods = [ "GET","POST" ])
def electronicBoomItemDelete():
    resp = { 'code':20000,'message':'删除成功~', 'data':{}}
    if request.method == 'POST':
        ids = request.values
        for key in ids:
            id = ids[key]
            ElectronicBoomItem.query.filter_by( id = id ).delete()
        db.session.commit()
    return jsonify( resp )

@route_api.route("/electronicBoomItem/add",methods = [ "GET","POST" ])
def electronicBoomItemAdd():
    resp = { 'code':20000,'message':'添加成功~', 'data':{}}
    if request.method == 'POST':
        data = request.get_data()
        json_data = json.loads(data.decode('utf-8'))
        boom_id = json_data['id']
        electronic_id = json_data['electronic_id']
        count = json_data['count']

        boom_info = ElectronicBoom.query.filter_by( id = boom_id ).first()
        electronic_info = Electronic.query.filter_by( id = electronic_id ).first()

        item = ElectronicBoomItem()
        item.electronic_id = electronic_info.id
        item.electronic_boom_id = boom_info.id
        item.count = count

        db.session.add(item)
        db.session.commit()

    return jsonify( resp )

@route_api.route("/electronicBoomItem/update",methods = [ "GET","POST" ])
def electronicBoomItemUpdate():
    resp = { 'code':20000,'message':'修改成功~', 'data':{}}
    req = request.values
    id = int( req['id'] ) if 'id' in req else 0
    count = int( req['count'] ) if 'count' in req else 0

    boom_item_info = ElectronicBoomItem.query.filter_by( id = id ).first()
    if not boom_item_info:
        resp['code'] = -1
        resp['message'] = '修改失败'
        return jsonify( resp )
    boom_item_info.count = count
    db.session.commit()

    return jsonify( resp )
